﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class CondFmt12Record : CondFmtRecordBase
    {
        private FrtRefHeaderU frtRefHeaderU = new FrtRefHeaderU() { rt = 0x0879};
        private CondFmtStructure mainCF;
        private List<CF12Record> _cf12Records = new List<CF12Record>();

        public CondFmt12Record(ConditionalFormatting conditionalFormatting, int id)
        {
            frtRefHeaderU.ref8 = (Ref8) conditionalFormatting.Range.Address;
            this.mainCF = new CondFmtStructure(conditionalFormatting, id);
        }

        public CondFmt12Record()
        {
        }

        protected override void ReadContent(BiffReaderContext context, int length)
        {
            Read(context.Reader);
        }

        private void Read(BinaryReader reader)
        {
#if DEBUG
            ReadWriteChecker.CheckClass((t, r) => t.Read(r), (t, w) => t.Write(w), reader, this);
#endif
            this.frtRefHeaderU.Read(reader);
            Contract.Assert(frtRefHeaderU.rt == 0x0879);
            mainCF.Read(reader);
        }

        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.CondFmt12; }
        }

        public List<CF12Record> CF12Records
        {
            get {
                return _cf12Records;
            }
        }

        internal override void WriteContent(BiffWriterWorkbookContext context)
        {
            Write(context.Writer);
        }

        private void Write(BinaryWriter writer)
        {
            frtRefHeaderU.grbitFrt = (FrtFlags) FrtFlags.fFrtAlert;
            frtRefHeaderU.Write(writer);
            mainCF.Write(writer);
        }

        protected override ConditionalFormatting ToConditionalFormatting(BiffReaderWorksheetContext context)
        {
            ConditionalFormatting result = new ConditionalFormatting();
            result.Range = mainCF.GetRange(context.Worksheet);
            foreach (var item in this.CF12Records)
            {
                result.Rules.Add(item.ToRule(context));
            }
            return result;
        }
    }
}